// 方形类
import 'dart:math';
import 'dart:ui';

import 'RandomShape.dart';

class RandomSquare extends RandomShape {
  double sideLength;

  RandomSquare({
    required Offset position,
    required double speedX,
    required double speedY,
    required Color color,
    required this.sideLength,
  }) : super(
    position: position,
    speedX: speedX,
    speedY: speedY,
    color: color,
  );

  @override
  void move(Size size) {
    position = Offset(position.dx + speedX, position.dy + speedY);
    double halfSide = sideLength / 2;
    bool hasCollision = false;

    // 检查水平方向是否碰撞
    if (position.dx - halfSide < 0 || position.dx + halfSide > size.width) {
      speedX = -speedX;
      hasCollision = true;
    }

    // 检查垂直方向是否碰撞
    if (position.dy - halfSide < 0 || position.dy + halfSide > size.height) {
      speedY = -speedY;
      hasCollision = true;
    }

    // 如果发生碰撞，重置计时
    if (hasCollision) {
      elapsedTime = 0;
    }
  }

  @override
  void draw(Canvas canvas, Size size) {
    if (isVisible) {
      Paint paint = Paint()..color = color;
      double halfSide = sideLength / 2;
      canvas.drawRect(
        Rect.fromLTWH(
          position.dx - halfSide,
          position.dy - halfSide,
          sideLength,
          sideLength,
        ),
        paint,
      );
    }
  }

  @override
  void updateVisibility(Size size) {
    elapsedTime += 16; // 假设每帧间隔 16 毫秒

    // 如果当前可见且达到可见时长，设置为不可见并重置计时
    if (isVisible && elapsedTime >= visibleDuration) {
      isVisible = false;
      elapsedTime = 0;
    }
    // 如果当前不可见且达到隐藏时长，设置为可见，重置计时并重置位置
    else if (!isVisible && elapsedTime >= invisibleDuration) {
      isVisible = true;
      elapsedTime = 0;
      resetPosition(size);
    }
  }

  @override
  bool isOutOfBounds(Size size) {
    double halfSide = sideLength / 2;
    return position.dx - halfSide < 0 || position.dx + halfSide > size.width ||
        position.dy - halfSide < 0 || position.dy + halfSide > size.height;
  }

  @override
  void resetPosition(Size size) {
    final random = Random();
    // 生成随机的横坐标，范围在 0 到屏幕宽度之间
    double newX = random.nextDouble() * size.width;
    // 生成随机的纵坐标，范围在 0 到屏幕高度之间
    double newY = random.nextDouble() * size.height;
    position = Offset(newX, newY);
  }
}